package com.usian.controller;

import com.usian.SSOFeign;
import com.usian.config.RedisClient;
import com.usian.feign.CartFeign;
import com.usian.pojo.TbItem;
import com.usian.pojo.TbUser;
import com.usian.utils.CookieUtils;
import com.usian.utils.JsonUtils;
import com.usian.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/frontend/sso")
public class SSOWebController {

    @Autowired
    private SSOFeign ssoFeign;

    @Autowired
    private CartFeign cartFeign;


    @Autowired
    private RedisClient redisClient;

    @Value("${CART_COOKIE_KEY}")
    private String CART_COOKIE_KEY;

    @Value("${CART_REDIS_KEY}")
    private String CART_REDIS_KEY;

    @RequestMapping("/checkUserInfo/{checkValue}/{checkFlag}")
    public Result checkUserInfo(@PathVariable String checkValue,@PathVariable Integer checkFlag){
        Boolean flag = ssoFeign.checkUserInfo(checkValue,checkFlag);
        if (flag){
            return Result.ok();
        }else {
            return Result.error("验证失败");
        }
    }

    /**
     * 注册
     * @param tbUser
     * @return
     */
    @RequestMapping("/userRegister")
    public Result userRegister(TbUser tbUser){
        Boolean flag = ssoFeign.userRegister(tbUser);
        if (flag){
            return Result.ok();
        }else {
            return Result.error("注册失败");
        }
    }

    /**
     * 登陆
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("userLogin")
    public Result userLogin(@RequestParam String username, @RequestParam String password,
                            HttpServletRequest request, HttpServletResponse response){
        Map<String,String> map = ssoFeign.userLogin(username,password);
        if (map!=null && map.size()>0){
            /* 登陆成功同步购物车 */
            /* 获取cookie中的数据 */
            String cookieValue = CookieUtils.getCookieValue(request, CART_COOKIE_KEY,true);
            /* 判空 */
            if (StringUtils.isNotBlank(cookieValue)) {
                Map<String, TbItem> cookieMap = JsonUtils.jsonToMap(cookieValue, TbItem.class);
                /* 获取redis中的商品信息 */
                Map<String, TbItem> redisMap =(Map<String, TbItem>) redisClient.hget(CART_REDIS_KEY, map.get("userid"));
                /* 判空 */
                if (redisMap!=null && redisMap.size()>0){
                    /* 如果redis中有数据cookie中也有数据，需要做数据合并。相同商品数量相加，不同商品添加一个新商品。 */
                    for (String redisKey : redisMap.keySet()) {
                        TbItem redisTbItem = redisMap.get(redisKey);
                        /* 判断cookieMap中是否包含遍历redisMap的这个商品 */
                        if (cookieMap.containsKey(redisKey)){
                            /* 存在数量相加 */
                            TbItem cookieTbItem = cookieMap.get(redisKey);
                            cookieTbItem.setNum(cookieTbItem.getNum()+redisTbItem.getNum());
                            cookieMap.put(redisKey,cookieTbItem);
                        }else {
                            /* 不存在添加新商品 */
                            cookieMap.put(redisKey,redisTbItem);
                        }
                    }
                }
                /* 更新redis中 */
                redisClient.hset(CART_REDIS_KEY,map.get("userid"),cookieMap);
                /* 删除cookie中的数据 */
                CookieUtils.deleteCookie(request,response,CART_COOKIE_KEY);
            }

            return Result.ok(map);
        }
        return Result.error("登陆失败");
    }

    @RequestMapping("getUserByToken/{token}")
    public Result getUserByToken(@PathVariable String token){
        TbUser tbUser = ssoFeign.getUserByToken(token);
        if (tbUser!=null){
            return Result.ok();
        }
        return null;
    }

    @RequestMapping("logOut")
    public Result logOut(@RequestParam String token){
        Integer resultNum = ssoFeign.logOut(token);
        if (resultNum==1){
            return Result.ok();
        }
        return Result.error("退出失败");
    }

}
